﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PhongMachTu.OModel;
using PhongMachTu.OConnection;

namespace PhongMachTu.OForm
{
    public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {
            if (OSession.isLoggedIn())
            {
                FormManager.mainForm.Show();
                FormManager.loginForm.Hide();
                this.txtPassword.Text = string.Empty;
                this.txtUsername.Text = string.Empty;
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text;
            string pwd = GetMD5Hash(txtPassword.Text);
            User loggedUser = DataManipulate.GetUserFromCredential(username, pwd);

            if (loggedUser != null)
            {
                OSession.LoggedInUser = loggedUser;
                OSession.LoginTime = DateTime.Now;

                txtPassword.Text = "";
                txtUsername.Text = "";
                FormManager.loginForm.Hide();

                //Phân quyền hiển thị button
                if (loggedUser.Type == 1)
                    FormManager.mainForm.disPlayButtonForDoctor();
                if (loggedUser.Type == 2)
                    FormManager.mainForm.disPlayButtonForReception();
                if (loggedUser.Type == 3)
                    FormManager.mainForm.disPlayButtonForAccountant();

                FormManager.mainForm.Show();
            }
            else
            {
                MessageBox.Show("Wrong Credential");
            }


        }

        //Produce MD5 from String
        public string GetMD5Hash(string input)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string password = s.ToString();
            return password;
        }
    }
}
